/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.model.clazz;

import java.sql.Connection;

import org.apache.commons.beanutils.PropertyUtils;

import com.koylu.caffein.converter.Converter;
import com.koylu.caffein.converter.OptimisticLockConverter;
import com.koylu.caffein.model.caffein.CaffeinConfig;
import com.koylu.caffein.model.container.ClazzContainer;

public class OptimisticLockProperty extends Property{
	
	private Converter converterObject = null;
	
	public OptimisticLockProperty() {
		setName("optimisticLock");
	}
	
	public Converter getConverter(CaffeinConfig caffeinConfig) throws Exception {
		if (converterObject == null) {
			int columnType = getColumnType(caffeinConfig);
			converterObject = new OptimisticLockConverter();
			converterObject.setFieldType(Long.class);
			converterObject.setJdbcType(columnType);
		}
		return converterObject;
	}
	
	public Class<?> toVirtualClass(CaffeinConfig caffeinConfig, Clazz clazz) throws Exception {
		return Long.class;
	}
	
	public boolean isColumnNullable(CaffeinConfig caffeinConfig) throws Exception {
		return false;
	}
	
	public boolean checkObjectVersion(CaffeinConfig caffeinConfig, Clazz clazz, Connection connection, ClazzContainer object) throws Exception{
		Object loadedObject = caffeinConfig.getCaffein().load(clazz, connection, object.getContainerId());
		if(loadedObject == null){
			return false;
		}
		if( (Long)PropertyUtils.getSimpleProperty(loadedObject, getName()) > (Long)PropertyUtils.getSimpleProperty(object, getName()) ){
			throw new RuntimeException("object is not up to date a newer object found in the table");
		}
		return true;
	}
}